package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapters.XJJLListAdapter;
import adapters.XJYSListAdapter;
import mytools.ApplicationUtil;
import mytools.MyBaseActivity;
import objects.HE_XJJL_Detail;
import objects.HE_XJMXXM;
import objects.HE_XJXM;
import objects.HE_XJXX_Detail;
import objects.HE_XJYS;
import objects.InPatient;
import objects.Section;
import objects.XJData;
import objects.XJ_UPDATE;
import service.WebService;

public class HEActivity extends MyBaseActivity implements ViewPager.OnPageChangeListener, SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemLongClickListener, BottomNavigationView.OnNavigationItemSelectedListener {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private int PAGE_NUM = 0;

    private ProgressDialog progressDialog = null;

    private List<HE_XJXX_Detail> mHEList;
    private List<HE_XJJL_Detail> mHERdList;
    private String mHEResult;
    private String mHERecordResult;
    private SwipeRefreshLayout mJKXJSwipe;
    private SwipeRefreshLayout mXJJLSwipe;
    private ExpandableListView mJKXJExpandable;
    private ExpandableListView mXJJLExpandable;
    private static BottomNavigationView bottomNavigationView;
    private XJYSListAdapter mXJYSAdapter;
    private XJJLListAdapter mXJJLAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_he);
        setNeedsMenuKey();
        onBindUI();

        mXJJLAdapter = new XJJLListAdapter(this);
        mXJYSAdapter = new XJYSListAdapter(this);
        HEPagerAdapter pagerAdapter = new HEPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(pagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(this);
    }

    private void onBindUI() {
        mTabLayout = findViewById(R.id.he_tab);
        mViewPager = findViewById(R.id.he_viewpager);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                PAGE_NUM = 0;
                doFlushData(true);
                break;
            case 1:
                if (bottomNavigationView.getVisibility() == View.VISIBLE) {
                    bottomNavigationView.setVisibility(View.GONE);
                }
                PAGE_NUM = 1;
                doFlushData(true);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        doFlushData(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && PAGE_NUM == 0) {
            int visibility = bottomNavigationView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;
            bottomNavigationView.setVisibility(visibility);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRefresh() {
        doFlushData(false);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        ExpandableListView expandableLV = PAGE_NUM == 0 ? mJKXJExpandable : mXJJLExpandable;
        final long packedPosition = expandableLV.getExpandableListPosition(position);
        final int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
        final int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
        if (childPosition != -1) {//长按的是group的时候，childPosition = -1
            AlertDialog.Builder builder = new AlertDialog.Builder(HEActivity.this);
            builder.setTitle("警告");
            builder.setMessage("您正在试图作废该条记录，确定要执行吗？");
            builder.setPositiveButton("确定", (dialog, which) -> {
                HE_XJJL_Detail heXjjlDetail = (HE_XJJL_Detail) mXJJLAdapter.getChild(groupPosition, childPosition);
                new MyCancelTask().execute(heXjjlDetail.getJLXH());
                doFlushData(true);
            });
            builder.setNegativeButton("取消", null);
            builder.show();
        }
        return true;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
//            case R.id.xj_action_1:
//                break;
            case R.id.xj_action_2: //保存健康宣教
                doCheck();
                break;
        }
        return false;
    }

    private class HEPagerAdapter extends FragmentPagerAdapter {

        HEPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }

        @Override
        public Fragment getItem(int position) {
            return new HEPlaceholderFragment().newInstance(position);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "宣教操作";
                case 1:
                    return "宣教记录";
            }
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

    public static class HEPlaceholderFragment extends Fragment {

        private final String ARG_SECTION_NUMBER = "section_number";
        HEActivity activity;

        public HEPlaceholderFragment newInstance(int sectionNumber) {
            HEPlaceholderFragment fragment = new HEPlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            WeakReference<HEActivity> mActivity = new WeakReference<>((HEActivity) context);
            activity = mActivity.get();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
            View rootView;
            switch (sectionNumber) {
                case 0:
                    rootView = inflater.inflate(R.layout.activity_heath_educate, container, false);
                    activity.mJKXJSwipe = rootView.findViewById(R.id.he_swipe_layout);
                    activity.mJKXJExpandable = rootView.findViewById(R.id.he_expandable_lv);
                    bottomNavigationView = rootView.findViewById(R.id.he_bottom_menu);
                    activity.mJKXJSwipe.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
                    activity.mJKXJSwipe.setOnRefreshListener(activity);
                    bottomNavigationView.setOnNavigationItemSelectedListener(activity);
                    activity.mJKXJExpandable.setAdapter(activity.mXJYSAdapter);
                    break;
                case 1:
                    rootView = inflater.inflate(R.layout.activity_heath_educate_records, container, false);
                    activity.mXJJLSwipe = rootView.findViewById(R.id.he_records_swiptelv);
                    activity.mXJJLExpandable = rootView.findViewById(R.id.he_records_expandablelv);
                    activity.mXJJLSwipe.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
                    activity.mXJJLSwipe.setOnRefreshListener(activity);
                    activity.mXJJLExpandable.setAdapter(activity.mXJJLAdapter);
                    activity.mXJJLExpandable.setOnItemLongClickListener(activity);
                    break;
                default:
                    return super.onCreateView(inflater, container, savedInstanceState);
            }
            return rootView;
        }
    }

    //显示虚拟菜单按钮
    private void setNeedsMenuKey() {
        try {
            Method setNeedsMenuKey = Window.class.getDeclaredMethod("setNeedsMenuKey", int.class);
            setNeedsMenuKey.setAccessible(true);
            int value = WindowManager.LayoutParams.class.getField("NEEDS_MENU_SET_TRUE").getInt(null);
            setNeedsMenuKey.invoke(getWindow(), value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取健康宣教
     */
    private class MyGetHETask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService getHEWebService = new WebService(HEActivity.this);
            getHEWebService.setMETHOD_NAME("getXJInfo");
            String result;
            getHEWebService.setPARMS(params);
            result = getHEWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取健康宣教列表为空！";
            } else {
                if (!result.equals(mHEResult)) {
                    mHEResult = result;
                    Gson gson = new Gson();
                    mHEList = gson.fromJson(mHEResult, new TypeToken<List<HE_XJXX_Detail>>() {
                    }.getType());
                    if (mHEList != null && mHEList.size() > 0) {
                        return null;
                    } else {
                        return "获取健康宣教表列表失败!";
                    }
                } else {
                    return "健康宣教数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String message) {
            super.onPostExecute(message);
            cancelProgressBar();
            if (mJKXJSwipe.isRefreshing()) {
                mJKXJSwipe.setRefreshing(false);
            }
            if (message != null) {
                Toast.makeText(HEActivity.this, message, Toast.LENGTH_SHORT).show();
            } else {
                List<HE_XJYS> xjysList = new ArrayList<>();
                for (HE_XJXX_Detail heDetail : mHEList
                        ) { //获取到的数据循环
                    int[] position = {0, 0};
                    boolean[] isContained = {false, false, false};
                    for (HE_XJYS xjys : xjysList) { //样式列表查询
                        if (heDetail.getYSBS().equals(xjys.getYSBS())) {
                            isContained[0] = true;
                            List<HE_XJXM> xmList = xjys.getList();
                            for (HE_XJXM xjxm : xmList
                                    ) {
                                if (heDetail.getXMBS().equals(xjxm.getXMBS())) {
                                    isContained[1] = true;
                                    List<HE_XJMXXM> mxList = xjxm.getList();
                                    for (HE_XJMXXM he_xjmxxm : mxList) {
                                        if (heDetail.getMXBS().equals(he_xjmxxm.getMXBS())) {
                                            isContained[2] = true;
                                            break;
                                        }
                                    }
                                    break;
                                }
                                position[1]++;
                            }
                            break;
                        }
                        position[0]++;
                    }
                    if (!isContained[0]) { //样式不存在
                        List<HE_XJMXXM> mxList = new ArrayList<>();//明细列表
                        mxList.add(new HE_XJMXXM(heDetail.getMXBS(), heDetail.getMXMC()));
                        HE_XJXM he_xjxm = new HE_XJXM(heDetail.getYSBS(), heDetail.getXMBS(), heDetail.getXMMC());
                        he_xjxm.setList(mxList);//宣教项目设置宣教明细列表
                        List<HE_XJXM> xmList = new ArrayList<>();//宣教项目列表
                        xmList.add(he_xjxm);
                        HE_XJYS he_xjys = new HE_XJYS(heDetail.getYSBS(), heDetail.getYSMC());
                        he_xjys.setList(xmList);//宣教样式设置宣教项目列表
                        xjysList.add(he_xjys);
                    } else if (!isContained[1]) { //项目不存在
                        List<HE_XJMXXM> mxList = new ArrayList<>();//明细列表
                        mxList.add(new HE_XJMXXM(heDetail.getMXBS(), heDetail.getMXMC()));
                        HE_XJXM he_xjxm = new HE_XJXM(heDetail.getYSBS(), heDetail.getXMBS(), heDetail.getXMMC());
                        he_xjxm.setList(mxList);//宣教项目设置宣教明细列表
                        xjysList.get(position[0]).getList().add(he_xjxm);
                    } else if (!isContained[2]) { //明细不存在
                        HE_XJMXXM he_xjmxxm = new HE_XJMXXM(heDetail.getMXBS(), heDetail.getMXMC());
                        xjysList.get(position[0]).getList().get(position[1]).getList().add(he_xjmxxm);
                    }
                }
                mXJYSAdapter.setmXJYSList(xjysList);
                for (int i = 0; i < mXJYSAdapter.getGroupCount(); i++) {
                    mJKXJExpandable.expandGroup(i);
                }
            }
        }
    }

    /**
     * 更新健康宣教数据
     */
    private class MyUpdateHETask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService updateHEWebService = new WebService(HEActivity.this);
            updateHEWebService.setMETHOD_NAME("updateXJJL");
            String result;
            updateHEWebService.setPARMS(params);
            result = updateHEWebService.getServerData();
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            cancelProgressBar();
            if (s != null) {
                Toast.makeText(HEActivity.this, "server: " + s, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 更新数据前检查
     */
    private void doCheck() {
        final Map<String, List<String>> dataSet = XJData.getDataSets();
        final List<XJ_UPDATE> xj_updates = new ArrayList<>();
        final Gson gson = new Gson();
        final String zyh = getMyApplication().getInPatient().getZYH();
        final String brbq = getMyApplication().getInPatient().getBRBQ();
        final String xjgh = getMyApplication().getUser().getYGDM();
        if (dataSet == null || dataSet.size() == 0) {
            Toast.makeText(HEActivity.this, "无选中数据！", Toast.LENGTH_SHORT).show();
        } else {
            //弹出宣教对象选择对话框
            final String[] xjdx_name = {"病人", "家属"};
            final String[] xjdx_value = {"0", "0"};
            AlertDialog.Builder builder = new AlertDialog.Builder(HEActivity.this).setTitle("宣教对象").setMultiChoiceItems(xjdx_name, null, (dialog, which, isChecked) -> {
                String isXJ = isChecked ? "1" : "0";
                xjdx_value[which] = isXJ;
            }).setPositiveButton("确定", (dialog, which) -> {
                if (xjdx_value[0].equals("0") && xjdx_value[1].equals("0")) {
                    Toast.makeText(HEActivity.this, "没有选择宣教对象！", Toast.LENGTH_SHORT).show();
                } else {
                    for (String key : dataSet.keySet()) {
                        List<String> xjxmList = dataSet.get(key);
                        String xjxm_json = gson.toJson(xjxmList, new TypeToken<List<String>>() {
                        }.getType());
                        String sbxh = getMyApplication().getDeviceInfos().get("SBXH");
                        xj_updates.add(new XJ_UPDATE(zyh, brbq, xjgh, key, xjdx_value[0], xjdx_value[1], xjxm_json, sbxh));
                    }
                    String update_json = gson.toJson(xj_updates, new TypeToken<List<XJ_UPDATE>>() {
                    }.getType());
                    if (update_json != null && !update_json.equals("")) {
                        String[] parms = {update_json};
                        showProgressBar(HEActivity.this);
                        new MyUpdateHETask().execute(parms);
                    }
                }
            }).setNegativeButton("取消", (dialog, which) -> {
            });
            builder.show();
        }
    }

    /**
     * 获取健康宣教记录
     */
    private class MyGetHERecordsTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService getHEWebService = new WebService(HEActivity.this);
            getHEWebService.setMETHOD_NAME("getXJJL");
            String result;
            getHEWebService.setPARMS(params);
            result = getHEWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取健康宣教记录为空！";
            } else {
                if (!result.equals(mHERecordResult)) {
                    mHERecordResult = result;
                    Gson gson = new Gson();
                    mHERdList = gson.fromJson(mHERecordResult, new TypeToken<List<HE_XJJL_Detail>>() {
                    }.getType());
                    if (mHERdList != null && mHERdList.size() > 0) {
                        return null;
                    } else {
                        return "获取健康宣教表记录失败!";
                    }
                } else {
                    return "健康宣教记录数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String message) {
            super.onPostExecute(message);
            if (mXJJLSwipe.isRefreshing()) {
                mXJJLSwipe.setRefreshing(false);
            }
            cancelProgressBar();
            if (message != null) {
                Toast.makeText(HEActivity.this, message, Toast.LENGTH_SHORT).show();
            } else {
                Map<HE_XJYS, List<HE_XJJL_Detail>> dataSets = new HashMap<>();
                List<HE_XJYS> xjysList = new ArrayList<>(dataSets.keySet());
                for (HE_XJJL_Detail heXjjlDetail : mHERdList) { //task获取到的数据循环
                    int position = 0;
                    boolean[] isContained = {false, false};
                    for (HE_XJYS heXjys : xjysList) {
                        if (heXjjlDetail.getYSBS().equals(heXjys.getYSBS())) {
                            isContained[0] = true;
                            List<HE_XJJL_Detail> xjjlList = dataSets.get(heXjys);
                            for (HE_XJJL_Detail xjxm : xjjlList) {
                                if (heXjjlDetail.getJLXH().equals(xjxm.getJLXH())) {
                                    isContained[1] = true;
                                    break;
                                }
                            }
                            break;
                        }
                        position++;
                    }
                    if (!isContained[0]) { //宣教样式不存在
                        HE_XJYS nXJYS = new HE_XJYS(heXjjlDetail.getYSBS(), heXjjlDetail.getYSMC());
                        xjysList.add(nXJYS);
                        List<HE_XJJL_Detail> xjxmList = new ArrayList<>();
                        xjxmList.add(heXjjlDetail);
                        dataSets.put(nXJYS, xjxmList);
                    } else if (!isContained[1]) { //宣教项目明细不存在
                        dataSets.get(xjysList.get(position)).add(heXjjlDetail);
                    }
                }
                mXJJLAdapter.setDataSets(dataSets);
//                mXJJLAdapter.notifyDataSetChanged();
                for (int i = 0; i < mXJJLAdapter.getGroupCount(); i++) { //全部展开
                    mXJJLExpandable.expandGroup(i);
                }
            }
        }
    }

    //作废宣教记录
    private class MyCancelTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService cancelHEWebService = new WebService(HEActivity.this);
            cancelHEWebService.setMETHOD_NAME("cancelXJJL");
            String result;
            cancelHEWebService.setPARMS(params);
            result = cancelHEWebService.getServerData();
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            String showInfo = Integer.valueOf(s) > 0 ? "作废成功！" : "作废失败！";
            Toast.makeText(HEActivity.this, showInfo, Toast.LENGTH_SHORT).show();
        }
    }

    //显示等待对话框
    private void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消显示等待对话框
    private void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    private void doFlushData(boolean isShowProgressBar) {
        switch (PAGE_NUM) {
            case 0:
                Section section = getMyApplication().getSection();
                if (section != null) {
                    String KSDM = section.getKSDM();
                    if (KSDM != null) {
                        if (isShowProgressBar) {
                            showProgressBar(this);
                        }
                        String[] parms = {KSDM};
                        new MyGetHETask().execute(parms);
                    }
                }
                break;
            case 1:
                InPatient inPatient = getMyApplication().getInPatient();
                if (inPatient != null) {
                    String ZYH = inPatient.getZYH();
                    if (ZYH != null) {
                        if (isShowProgressBar) {
                            showProgressBar(this);
                        }
                        String[] parms = {ZYH};
                        new MyGetHERecordsTask().execute(parms);
                    }
                }
                break;
        }
    }

}